import time
import asyncio
import concurrent.futures
from random import randint

def func1(value):
    time.sleep(randint(1, 2))
    print(value)
    return value

async def main():
    loop = asyncio.get_running_loop()

    futs = []
    # for i in range(10):
    #     # 1. 内部会先调用 ThreadPoolExecutor的submit方法去线程池中申请一个线程去执行func1函数，并返回一个concurrent.futures.Future对象
    #     # 2. 调用asyncio.wrap_future对象将concurrent.futures.Future包装为asyncio.Future对象。这样就能支持await关键字
    #     fut = loop.run_in_executor(None, func1, i)
    #     futs.append(fut)
    # r1, r2 = await asyncio.wait(futs)
    # print(r1, r2)

    with concurrent.futures.ThreadPoolExecutor() as pool:
        for i in range(10):
            futs.append(loop.run_in_executor(pool, func1, i))

    # with concurrent.futures.ProcessPoolExecutor() as pool:
    #     for i in range(10):
    #         futs.append(loop.run_in_executor(pool, func1, i))

    r1, r2 = await asyncio.wait(futs)
    print(r1)
    print('---------------')
    for f in r1:
        print('result', f.result())
    print(r2)

if __name__ == '__main__':
    asyncio.run(main())
